#include <stdio.h>
#include <stdlib.h>

int main()
{
    int t = 0;
    scanf("%d", &t);
    while(t--)
    {
        int n = 0;
        scanf("%d", &n);
        char arr[n+1];
        scanf("%s", arr);

        int sum = 0;
        int count1 = 0;
        int count2 = 0;
        for(int j = 0; j < n; j++)
        {
            if(arr[j] == '(')
            {
                count1++;
            }
            else
            {
                if(count1 > 0)
                count1--;
                else
                count2++;
            }
            sum += count1 > count2 ? count1 : count2;
        }

        int all = sum;
        for(int i = 0; i < n - 1; i++)
        {
            sum -= count1 > count2 ? count1 : count2;
            if(arr[i] == '(')
            {
                if(count1 > 0)
                count1--;
                else
                count2++;
            }
            else
            {
                if(count2 > 0)
                count2--;
                else
                count1++;
            }
            all += sum;
        }

        printf("%d\n", all);
    }
    return 0;
}